import React, { useState, useEffect } from 'react';
import { connect, useDispatch } from 'umi';
import { message, Button, Table, Input, Select, Form, Row, Col, Modal } from 'antd';
import styles from './index.less';

const layout = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
};

const RolePage = (props) => {
  const {
    authActManageModel,
    common,
    loading: { effects },
    onOk,
    onCancel,
    iRoleVis = false,
    appCodeOfSelect,
  } = props;
  const { userInfo = {} } = common;
  const dispatch = useDispatch();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [roleListTotal, setRoleListTotal] = useState(0);
  const [roleList, setRoleList] = useState([]);
  const [pageIndex, setpageIndex] = useState(1);
  const [pageSize, setpageSize] = useState(7);
  const [form] = Form.useForm();
  const [formData, setFormData] = useState({});
  const [confirmLoading, setconfirmLoading] = useState(false);

  // useImperativeHandle(ref, () => ({
  //   handleSubmit,
  // }));

  useEffect(() => {
    if (!appCodeOfSelect) return;
    dispatch({
      type: 'authActManageModel/getImportRoleList',
      payload: { pageIndex, pageSize, appCode: appCodeOfSelect, ...formData },
    }).then((res) => {
      if (res.code === 0 && res.data) {
        const { dataList, total } = res.data;
        setRoleListTotal(total);
        setRoleList(dataList);
      } else {
        message.error(res.message);
      }
    });
    return () => {};
  }, [pageIndex, pageSize, formData, appCodeOfSelect]);

  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const param = { ...values };
      setFormData(param);
      setpageIndex(1);
    });
  };

  const handleReset = () => {
    form.resetFields();
    setpageIndex(1);
    setFormData({});
  };

  const onSelectChange = (rowKeys) => {
    setSelectedRowKeys(rowKeys);
    // setRoleCode(rowKeys[0]);
  };

  const onRowClick = (rows) => {
    setSelectedRowKeys([rows.roleCode]);
    // setRoleCode(rows.roleCode);
  };

  const rowSelection = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const onSetRoleRes = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('未选择角色！');
      return;
    }
    setconfirmLoading(true);
    dispatch({
      type: 'authActManageModel/getAuthByRoleCodethen',
      payload: { roleCode: selectedRowKeys[0], appCode: appCodeOfSelect },
    }).then((res) => {
      if (res.code === 0) {
        onOk(res.data?.actionMap || {});
      } else {
        message.error(res.message);
      }
      setconfirmLoading(false);
    });
  };

  // const handleTableChange = (pagination, filters, sorter) => {
  //   setCurrent(pagination.current);
  // };
  const columns = [
    {
      title: '名称',
      dataIndex: 'roleName',
      key: 'roleName',
      ellipsis: true,
    },
    {
      title: '编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'roleType',
      key: 'roleType',
      ellipsis: true,
      render: (text) => (text === 1 ? '组织角色' : '公共角色'),
    },
    {
      title: '组织',
      dataIndex: 'orgList',
      key: 'orgList',
      ellipsis: true,
      render: (text) => text && text.length > 0 && text[0].orgName,
    },
    {
      title: '描述',
      dataIndex: 'roleDesc',
      key: 'roleDesc',
      ellipsis: true,
    },
  ];

  return (
    <Modal
      title={'选择角色'}
      confirmLoading={confirmLoading}
      visible={iRoleVis}
      onOk={onSetRoleRes}
      onCancel={onCancel}
    >
      <div className={styles.root}>
        <div className={styles.menuTitleWrapper}>
          <Form {...layout} form={form} name="advanced_search">
            <Row>
              <Col span={12}>
                <Form.Item name="roleType" label="角色类型">
                  <Select placeholder="请选择" style={{ width: '90%' }} allowClear>
                    <Select.Option value={0}>公共角色</Select.Option>
                    <Select.Option value={1}>组织角色</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="roleName" label="角色名称">
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item name="roleCode" label="角色编码">
                  <Input placeholder="请输入" maxLength="6" style={{ width: '90%' }} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item labelCol={0} wrapperCol={24}>
                  <Button style={{ marginLeft: 10 }} type="primary" onClick={handleSearch}>
                    查询
                  </Button>
                  <Button style={{ marginLeft: 16 }} onClick={handleReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.menuTable}>
          <Table
            onRow={(record) => {
              return {
                onClick: () => onRowClick(record),
              };
            }}
            rowSelection={rowSelection}
            rowKey="roleCode"
            columns={columns}
            dataSource={roleList}
            size="small"
            pagination={{
              total: roleListTotal,
              pageSize,
              current: pageIndex,
              showSizeChanger: true,
              pageSizeOptions: [5, 10, 50, 100],
              size: 'small',
              onChange: (page) => {
                setpageIndex(page);
              },
              onShowSizeChange: (_, pageSize) => {
                setpageSize(pageSize);
              },
            }}
            // scroll={{ y: 260 }}
            // onChange={handleTableChange}
            loading={effects['authActManageModel/getImportRoleList']}
          />
        </div>
      </div>
    </Modal>
  );
};

export default connect((state) => state)(RolePage);
